package com.example.sprintboot.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.sprintboot.entity.Product;
import com.example.sprintboot.service.ProductService;
import com.example.sprintboot.util.JwtUtils;
import com.example.sprintboot.vo.ProductBannerVO;
import com.example.sprintboot.vo.ProductDetailVO;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import com.example.sprintboot.security.UserDetailsImpl;

@RestController
@RequestMapping("/api/products")
public class ProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private JwtUtils jwtUtils;

    // 搜索商品列表
    @GetMapping
    public Map<String, Object> list(@RequestParam(defaultValue = "1") int page,
                                    @RequestParam(defaultValue = "10") int pageSize,
                                    @RequestParam(required = false) String keyword,
                                    @RequestParam(required = false) Integer categoryId,
                                    @RequestParam(required = false) Integer status) {
        // 如果status未传，默认只查在售商品
        if (status == null) status = 1;
        IPage<Product> result = productService.getProductPage(page, pageSize, keyword, categoryId, status);
        Map<String, Object> map = new HashMap<>();
        map.put("total", result.getTotal());
        map.put("page", result.getCurrent());
        map.put("pageSize", result.getSize());
        map.put("list", result.getRecords());
        return map;
    }

    // 获取轮播图商品
    @GetMapping("/banner")
    public List<ProductBannerVO> getBannerProducts() {
        return productService.getBannerProducts();
    }

    // 获取商品详情
    @GetMapping("/{id}")
    public ProductDetailVO detail(@PathVariable Integer id) {
        ProductDetailVO vo = productService.getProductDetailById(id);
        // 只允许在售商品被访问
        if (vo == null || vo.getStatus() == null || vo.getStatus() != 1) {
            throw new RuntimeException("商品不存在或未审核通过");
        }
        return vo;
    }

    // 添加商品
    @PostMapping
    public Map<String, Object> add(@RequestBody Product product) {
        Map<String, Object> map = new HashMap<>();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !(authentication.getPrincipal() instanceof UserDetailsImpl)) {
            map.put("success", false);
            map.put("message", "用户未登录");
            return map;
        }
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        Integer userId = userDetails.getUserId();
        String role = userDetails.getUser().getRole().name().toLowerCase();
        boolean success = productService.addProduct(product, userId, role);
        map.put("success", success);
        return map;
    }

    // 编辑商品
    @PutMapping("/{id}")
    public Map<String, Object> update(@PathVariable Integer id, @RequestBody Product product) {
        Map<String, Object> map = new HashMap<>();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !(authentication.getPrincipal() instanceof UserDetailsImpl)) {
            map.put("success", false);
            map.put("message", "用户未登录");
            return map;
        }
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        Integer userId = userDetails.getUserId();
        String role = userDetails.getUser().getRole().name().toLowerCase();
        product.setProductId(id);
        boolean success = productService.updateProduct(product, userId, role);
        map.put("success", success);
        return map;
    }

    // 删除商品
    @DeleteMapping("/{id}")
    public Map<String, Object> delete(@PathVariable Integer id) {
        Map<String, Object> map = new HashMap<>();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !(authentication.getPrincipal() instanceof UserDetailsImpl)) {
            map.put("success", false);
            map.put("message", "用户未登录");
            return map;
        }
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        Integer userId = userDetails.getUserId();
        String role = userDetails.getUser().getRole().name().toLowerCase();
        boolean success = productService.deleteProduct(id, userId, role);
        map.put("success", success);
        return map;
    }
} 